{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!--BOOK_INFORMATION-->\n",
    "<img align=\"left\" style=\"padding-right:10px;\" src=\"fig/cover-small.jpg\">\n",
    "*This notebook contains an excerpt from the [Whirlwind Tour of Python](http://www.oreilly.com/programming/free/a-whirlwind-tour-of-python.csp) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jakevdp/WhirlwindTourOfPython).*\n",
    "\n",
    "*The text and code are released under the [CC0](https://github.com/jakevdp/WhirlwindTourOfPython/blob/master/LICENSE) license; see also the companion project, the [Python Data Science Handbook](https://github.com/jakevdp/PythonDataScienceHandbook).*\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!--NAVIGATION-->\n",
    "< [How to Run Python Code](01-How-to-Run-Python-Code.ipynb) | [Contents](Index.ipynb) | [Basic Python Semantics: Variables and Objects](03-Semantics-Variables.ipynb) >"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# A Quick Tour of Python Language Syntax"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python was originally developed as a teaching language, but its ease of use and clean syntax have led it to be embraced by beginners and experts alike.\n",
    "The cleanliness of Python's syntax has led some to call it \"executable pseudocode\", and indeed my own experience has been that it is often much easier to read and understand a Python script than to read a similar script written in, say, C.\n",
    "Here we'll begin to discuss the main features of Python's syntax.\n",
    "\n",
    "Syntax refers to the structure of the language (i.e., what constitutes a correctly-formed program).\n",
    "For the time being, we'll not focus on the semantics – the meaning of the words and symbols within the syntax – but will return to this at a later point.\n",
    "\n",
    "Consider the following code example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "lower: [0, 1, 2, 3, 4]\n",
      "upper: [5, 6, 7, 8, 9]\n"
     ]
    }
   ],
   "source": [
    "# set the midpoint\n",
    "midpoint = 5\n",
    "\n",
    "# make two empty lists\n",
    "lower = []; upper = []\n",
    "\n",
    "# split the numbers into lower and upper\n",
    "for i in range(10):\n",
    "    if (i < midpoint):\n",
    "        lower.append(i)\n",
    "    else:\n",
    "        upper.append(i)\n",
    "        \n",
    "print(\"lower:\", lower)\n",
    "print(\"upper:\", upper)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This script is a bit silly, but it compactly illustrates several of the important aspects of Python syntax.\n",
    "Let's walk through it and discuss some of the syntactical features of Python"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comments Are Marked by ``#``\n",
    "The script starts with a comment:\n",
    "``` python\n",
    "# set the midpoint\n",
    "```\n",
    "Comments in Python are indicated by a pound sign (``#``), and anything on the line following the pound sign is ignored by the interpreter.\n",
    "This means, for example, that you can have stand-alone comments like the one just shown, as well as inline comments that follow a statement. For example:\n",
    "``` python\n",
    "x += 2  # shorthand for x = x + 2\n",
    "```\n",
    "Python does not have any syntax for multi-line comments, such as the ``/* ... */`` syntax used in C and C++, though multi-line strings are often used as a replacement for multi-line comments (more on this in [String Manipulation and Regular Expressions](14-Strings-and-Regular-Expressions.ipynb))."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## End-of-Line Terminates a Statement\n",
    "The next line in the script is\n",
    "``` python\n",
    "midpoint = 5\n",
    "```\n",
    "This is an assignment operation, where we've created a variable named ``midpoint`` and assigned it the value ``5``.\n",
    "Notice that the end of this statement is simply marked by the end of the line.\n",
    "This is in contrast to languages like C and C++, where every statement must end with a semicolon (``;``).\n",
    "\n",
    "In Python, if you'd like a statement to continue to the next line, it is possible to use the \"``\\``\" marker to indicate this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "x = 1 + 2 + 3 + 4 +\\\n",
    "    5 + 6 + 7 + 8"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is also possible to continue expressions on the next line within parentheses, without using the \"``\\``\" marker:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "x = (1 + 2 + 3 + 4 +\n",
    "     5 + 6 + 7 + 8)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Most Python style guides recommend the second version of line continuation (within parentheses) to the first (use of the \"``\\``\" marker)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Semicolon Can Optionally Terminate a Statement\n",
    "Sometimes it can be useful to put multiple statements on a single line.\n",
    "The next portion of the script is\n",
    "``` python\n",
    "lower = []; upper = []\n",
    "```\n",
    "This shows the example of how the semicolon (``;``) familiar in C can be used optionally in Python to put two statements on a single line.\n",
    "Functionally, this is entirely equivalent to writing\n",
    "``` python\n",
    "lower = []\n",
    "upper = []\n",
    "```\n",
    "Using a semicolon to put multiple statements on a single line is generally discouraged by most Python style guides, though occasionally it proves convenient."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Indentation: Whitespace Matters!\n",
    "Next, we get to the main block of code:\n",
    "``` Python\n",
    "for i in range(10):\n",
    "    if i < midpoint:\n",
    "        lower.append(i)\n",
    "    else:\n",
    "        upper.append(i)\n",
    "```\n",
    "This is a compound control-flow statement including a loop and a conditional – we'll look at these types of statements in a moment.\n",
    "For now, consider that this demonstrates what is perhaps the most controversial feature of Python's syntax: whitespace is meaningful!\n",
    "\n",
    "In programming languages, a *block* of code is a set of statements that should be treated as a unit.\n",
    "In C, for example, code blocks are denoted by curly braces:\n",
    "``` C\n",
    "// C code\n",
    "for(int i=0; i<100; i++)\n",
    "   {\n",
    "      // curly braces indicate code block\n",
    "      total += i;\n",
    "   }\n",
    "```\n",
    "In Python, code blocks are denoted by *indentation*:\n",
    "``` python\n",
    "for i in range(100):\n",
    "    # indentation indicates code block\n",
    "    total += i\n",
    "```\n",
    "In Python, indented code blocks are always preceded by a colon (``:``) on the previous line."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The use of indentation helps to enforce the uniform, readable style that many find appealing in Python code.\n",
    "But it might be confusing to the uninitiated; for example, the following two snippets will produce different results:\n",
    "```python\n",
    ">>> if x < 4:         >>> if x < 4:\n",
    "...     y = x * 2     ...     y = x * 2\n",
    "...     print(x)      ... print(x)\n",
    "```\n",
    "In the snippet on the left, ``print(x)`` is in the indented block, and will be executed only if ``x`` is less than ``4``.\n",
    "In the snippet on the right ``print(x)`` is outside the block, and will be executed regardless of the value of ``x``!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python's use of meaningful whitespace often is surprising to programmers who are accustomed to other languages, but in practice it can lead to much more consistent and readable code than languages that do not enforce indentation of code blocks.\n",
    "If you find Python's use of whitespace disagreeable, I'd encourage you to give it a try: as I did, you may find that you come to appreciate it.\n",
    "\n",
    "Finally, you should be aware that the *amount* of whitespace used for indenting code blocks is up to the user, as long as it is consistent throughout the script.\n",
    "By convention, most style guides recommend to indent code blocks by four spaces, and that is the convention we will follow in this report.\n",
    "Note that many text editors like Emacs and Vim contain Python modes that do four-space indentation automatically."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Whitespace *Within* Lines Does Not Matter\n",
    "While the mantra of *meaningful whitespace* holds true for whitespace *before* lines (which indicate a code block), white space *within* lines of Python code does not matter.\n",
    "For example, all three of these expressions are equivalent:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "x=1+2\n",
    "x = 1 + 2\n",
    "x             =        1    +                2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Abusing this flexibility can lead to issues with code readibility – in fact, abusing white space is often one of the primary means of intentionally obfuscating code (which some people do for sport).\n",
    "Using whitespace effectively can lead to much more readable code, \n",
    "especially in cases where operators follow each other – compare the following two expressions for exponentiating by a negative number:\n",
    "``` python\n",
    "x=10**-2\n",
    "```\n",
    "to\n",
    "``` python\n",
    "x = 10 ** -2\n",
    "```\n",
    "I find the second version with spaces much more easily readable at a single glance.\n",
    "Most Python style guides recommend using a single space around binary operators, and no space around unary operators.\n",
    "We'll discuss Python's operators further in [Basic Python Semantics: Operators](04-Semantics-Operators.ipynb)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Parentheses Are for Grouping or Calling\n",
    "\n",
    "In the previous code snippet, we see two uses of parentheses.\n",
    "First, they can be used in the typical way to group statements or mathematical operations:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "14"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "2 * (3 + 4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "They can also be used to indicate that a *function* is being called.\n",
    "In the next snippet, the ``print()`` function is used to display the contents of a variable (see the sidebar).\n",
    "The function call is indicated by a pair of opening and closing parentheses, with the *arguments* to the function contained within:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "first value: 1\n"
     ]
    }
   ],
   "source": [
    "print('first value:', 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "second value: 2\n"
     ]
    }
   ],
   "source": [
    "print('second value:', 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Some functions can be called with no arguments at all, in which case the opening and closing parentheses still must be used to indicate a function evaluation.\n",
    "An example of this is the ``sort`` method of lists:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4]\n"
     ]
    }
   ],
   "source": [
    "L = [4,2,3,1]\n",
    "L.sort()\n",
    "print(L)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The \"``()``\" after ``sort`` indicates that the function should be executed, and is required even if no arguments are necessary."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Aside: A Note on the ``print()`` Function\n",
    "\n",
    "Above we used the example of the ``print()`` function.\n",
    "The ``print()`` function is one piece that has changed between Python *2.x* and Python *3.x*. In Python 2, ``print`` behaved as a statement: that is, you could write\n",
    "``` python\n",
    "# Python 2 only!\n",
    ">> print \"first value:\", 1\n",
    "first value: 1\n",
    "```\n",
    "For various reasons, the language maintainers decided that in Python 3 ``print()`` should become a function, so we now write\n",
    "``` python\n",
    "# Python 3 only!\n",
    ">>> print(\"first value:\", 1)\n",
    "first value: 1\n",
    "```\n",
    "This is one of the many backward-incompatible constructs between Python 2 and 3.\n",
    "As of the writing of this book, it is common to find examples written in both versions of Python, and the presence of the ``print`` statement rather than the ``print()`` function is often one of the first signs that you're looking at Python 2 code."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Finishing Up and Learning More\n",
    "\n",
    "This has been a very brief exploration of the essential features of Python syntax; its purpose is to give you a good frame of reference for when you're reading the code in later sections.\n",
    "Several times we've mentioned Python \"style guides\", which can help teams to write code in a consistent style.\n",
    "The most widely used style guide in Python is known as PEP8, and can be found at https://www.python.org/dev/peps/pep-0008/.\n",
    "As you begin to write more Python code, it would be useful to read through this!\n",
    "The style suggestions contain the wisdom of many Python gurus, and most suggestions go beyond simple pedantry: they are experience-based recommendations that can help avoid subtle mistakes and bugs in your code."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!--NAVIGATION-->\n",
    "< [How to Run Python Code](01-How-to-Run-Python-Code.ipynb) | [Contents](Index.ipynb) | [Basic Python Semantics: Variables and Objects](03-Semantics-Variables.ipynb) >"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
